import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createContainer } from 'utils/hoc'
import ContentBox from 'components/contentBox'
import Filters from 'components/common/filters'
import { Form, message, Button, Input, Select, Table } from 'antd'
import { widgetType } from 'constants'
import PropTypes from 'prop-types'
import Style from './banner.css'

const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 16 }
}

const { TextArea } = Input
const { Option } = Select
class IndexForm extends Component {
  static propTypes = {
    form: PropTypes.object,
    getPushed: PropTypes.func,
    pushedData: PropTypes.object,
    getAuthorList: PropTypes.func
  }
  constructor (props) {
    super(props)
    this.state = {
      pageNo: 1,
      pageSize: 3,
      params: {},
      editParams: {},
      selectedRowKeys: [],
      data: []
    }
    this.search = this.search.bind(this)
    this.reset = this.reset.bind(this)
    this.onPageChange = this.onPageChange.bind(this)
    this.onShowSizeChange = this.onShowSizeChange.bind(this)
    this.onSelectChange = this.onSelectChange.bind(this)
    this.handleOk = this.handleOk.bind(this)
    this.msgTypeChange = this.msgTypeChange.bind(this)
  }

  getFilterCols (category, author) {
    return [
      {
        label: '输入搜索',
        id: 'searchField',
        widget: widgetType.input,
        placeholder: '请输入'
      }, {
        label: '会员等级',
        id: 'memberLevelEnum',
        widget: widgetType.select,
        placeholder: '请选择',
        options: [{
          text: '普通会员',
          value: 'NORMAL_LEVEL'
        }, {
          text: '尊享会员',
          value: 'PAY_LEVEL'
        }]
      }, {
        label: '邀请亲友数',
        id: 'invitationNum',
        widget: widgetType.input,
        placeholder: '请输入'
      }, {
        label: '消费次数',
        id: 'consumptionCount',
        widget: widgetType.input,
        placeholder: '请输入'
      }, {
        label: 'Min消费金额',
        id: 'consumptionAmountMin',
        widget: widgetType.input,
        placeholder: '请输入最低消费金额'
      }, {
        label: 'Max消费金额',
        id: 'consumptionAmountMax',
        widget: widgetType.input,
        placeholder: '请输入最高消费金额'
      }, {
        label: '最近消费',
        id: 'lastPurchaseTime',
        widget: widgetType.datePicker,
        placeholder: '请选择'
      }
    ]
  }

  getTableCols () {
    return [
      {
        title: '用户ID',
        dataIndex: 'userId',
        key: 'userId',
        width: 150
      },
      {
        title: '用户手机号',
        dataIndex: 'mobile',
        key: 'mobile',
        width: 100
      },
      {
        title: '会员等级',
        dataIndex: 'memberLevel',
        key: 'memberLevel',
        width: 100
      },
      {
        title: '消费金额',
        dataIndex: 'time',
        key: 'time',
        width: 150,
        render: text => text / 100 || '-'
      },
      {
        title: '消费次数',
        dataIndex: 'consumptionAmount',
        key: 'consumptionAmount',
        width: 100
      },
      {
        title: '订单均价',
        dataIndex: 'orderAverageAmount',
        key: 'orderAverageAmount',
        width: 100
      },
      {
        title: '最近购买时间',
        dataIndex: 'lastPurchaseTime',
        key: 'lastPurchaseTime',
        width: 100,
        render: text => text || '-'
      }
    ]
  }

  reset () {
    this.setState({
      pageNo: 1,
      pageSize: 20,
      params: {}
    })
    this.props.getPushed({
      pageNo: 1,
      pageSize: 20
    })
  }

  search (values = {}) {
    const { pageSize, pageNo } = this.state
    values.pageNo = pageNo
    values.pageSize = pageSize
    if (values.lastPurchaseTime) {
      values.lastPurchaseTime = values.lastPurchaseTime.format('YYYY-MM-DD HH:mm:ss')
    }
    this.setState({
      params: values
    })
    this.props.getPushed(values)
  }

  handleOk () {
    const { editParams, reveiveUsers } = this.state
    this.props.form.validateFieldsAndScroll((err, values) => {
      values.reveiveUsers = reveiveUsers
      values.pushType = 2
      if (!err) {
        values.id = editParams.id
        this.props.editPush(values)
      }
    })
  }

  onPageChange (pageNo, pageSize) {
    const { params } = this.state
    params.pageNo = pageNo
    params.pageSize = pageSize
    this.setState({
      pageNo
    })
    this.props.getPushed(params)
  }

  onShowSizeChange (current, pageSize) {
    this.setState({
      pageSize
    })
    const { params } = this.state
    params.pageNo = current
    params.pageSize = pageSize
    this.props.getPushed(params)
  }

  onSelectChange (selectedRowKeys, selectedRows) {
    const idList = []
    const nameList = []
    selectedRows.map(item => {
      idList.push(item.userId)
      nameList.push(item.userName)
    })

    this.setState({
      reveiveUsers: idList.join(','),
      selectedRowKeys,
      reveiveUserName: `${nameList.join(',')}  共(${selectedRows.length})人`
    })
  }

  msgTypeChange (value) {
    if (value === 'COMMODITY_NEW') {
      this.setState({
        msgType: value
      })
      this.props.getAuthorList()
    } else {
      this.setState({
        msgType: value
      })
    }
  }

  componentDidMount () {
    const { id } = this.props.match.params
    const { pageNo } = this.state
    this.props.getPushed({
      pageSize: 999999,
      pageNo
    })
    setTimeout(() => {
      this.props.getPushDetail({
        id
      })
    }, 300)
  }

  componentWillReceiveProps (nextProps) {
    if (!this.props.editPushRequest && nextProps.editPushRequest) {
      message.success('编辑成功')
      this.props.router.replace('/operation/push')
    }

    if (!this.props.createPushRequest && nextProps.createPushRequest) {
      this.props.router.replace('/operation/push')
      message.success('创建成功')
    }

    if (!this.props.pushDetail && nextProps.pushDetail) {
      const selectedRowKeys = []
      const pushedUser = nextProps.pushedData && nextProps.pushedData.list
      const userNameList = []
      const idList = []
      nextProps.pushDetail.reveiveUserList && nextProps.pushDetail.reveiveUserList.forEach(element => {
        userNameList.push(element.userName)
        idList.push(element.userId)
        pushedUser && pushedUser.forEach((item, index) => {
          if (element.userId === item.userId) {
            selectedRowKeys.push(index)
          }
        })
      })

      this.setState({
        showModal: true,
        editParams: nextProps.pushDetail,
        reveiveUserName: userNameList.join(','),
        idList,
        selectedRowKeys
      })
    }

    if (!this.props.pushedData && nextProps.pushedData) {
      nextProps.pushedData.list.map((element, index) => {
        element.key = index
      })

      this.setState({
        data: nextProps.pushedData.list
      })
    }
  }

  render () {
    const { getFieldDecorator } = this.props.form

    const { selectedRowKeys, msgType, reveiveUserName, editParams, data } = this.state
    const { pushedData, authorOptionsList = [] } = this.props

    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange
    }

    return (
      <>
        <ContentBox>
          <div className={Style['scenes-RecycleForm']}>
            <Filters
              cols={this.getFilterCols()}
              search={this.search} />
            <Table
              rowSelection={rowSelection}
              size='small'
              loading={!pushedData}
              columns={this.getTableCols()}
              dataSource={data}
            />
          </div>
          <Form {...formItemLayout} id='add'>
            <Form.Item label='消息标题'>
              {getFieldDecorator('pushTitle', {
                initialValue: editParams.pushTitle,
                rules: [{ required: true, message: '请输入消息标题' }]
              })(
                <Input placeholder='请输入' style={{ width: '400px' }} />
              )}
            </Form.Item>
            <Form.Item label='消息内容'>
              {getFieldDecorator('pushContent', {
                initialValue: editParams.pushContent,
                rules: [{ required: true, message: '请输入消息内容' }]
              })(
                <TextArea placeholder='请输入' style={{ width: '400px' }} />
              )}
            </Form.Item>
            <Form.Item label='消息类型'>
              {getFieldDecorator('msgType', {
                initialValue: editParams.msgType
              })(
                <Select placeholder='请输入' onChange={this.msgTypeChange} style={{ width: '400px' }} >
                  <Option value='SPECIFIC_EVENT'>官方特定事件</Option>
                  <Option value='COMMODITY_NEW'>艺术家作品上新</Option>
                </Select>)}
            </Form.Item>
            {
              msgType === 'COMMODITY_NEW' && <Form.Item label='创作者'>
                {getFieldDecorator('authorId', {
                  initialValue: editParams.authorId,
                  rules: [
                    { required: true, message: '请选择创作者!' }
                  ]
                })(
                  <Select placeholder='请选择创作者' style={{ width: '400px' }} >
                    {
                      authorOptionsList && authorOptionsList.map((item, index) => <Option key={item.value} value={item.value}>{item.text}</Option>
                      )
                    }
                  </Select>
                )}
              </Form.Item>
            }
            <Form.Item label='发布对象'>
              {getFieldDecorator('remark', {
                initialValue: reveiveUserName,
                rules: [{ required: true, message: '请输选择布对象' }]
              })(
                <TextArea disabled placeholder='请输入' style={{ width: '400px' }} />
              )}
            </Form.Item>
          </Form>
          <div style={{ width: '100%', display: 'flex', justifyContent: 'center', margin: '20px 0' }}>
            <Button type='primary' onClick={this.handleOk}>发布</Button>
          </div>
        </ContentBox>
      </>
    )
  }
}

const mapState = state => ({
  pushedData: state.operation.pushedData,
  createPushRequest: state.operation.createPushRequest,
  editPushRequest: state.operation.editPushRequest,
  authorOptionsList: state.goods.authorOptionsList,
  pushDetail: state.operation.pushDetail
})
const mapDispatch = dispatch => ({
  getPushed: dispatch.operation.getPushed,
  createPush: dispatch.operation.createPush,
  editPush: dispatch.operation.editPush,
  getAuthorList: dispatch.goods.getAuthorList,
  getPushDetail: dispatch.operation.getPushDetail
})

const Index = Form.create({ name: 'dynamic_rule' })(IndexForm)

export default createContainer(
  connect(
    mapState,
    mapDispatch
  )(Index)
)
